package dao

import (
	"github.com/xormplus/xorm"
	"shoping.zozoo.net/model"
)

//定义接口
type ProductInterface interface {
	Insert(*model.Product) (int64, error)
	Del(int64) (bool, error)
	Update(*model.Product) error
	SelectById(int64) (*model.Product, error)
	SelectAll() ([]*model.Product, error)
}

type ProductDao struct {
	*xorm.Engine
}

//获取dao实例列表
func NewProductDao(orm *xorm.Engine) ProductInterface {
	return &ProductDao{
		orm,
	}
}

//插入数据
func (p *ProductDao) Insert(product *model.Product) (id int64, err error) {
	id, err = p.InsertOne(product)
	return
}

//删除数据
func (p *ProductDao) Del(id int64) (ok bool, err error) {
	if _, err = p.Delete(id); err != nil {
		return false, err
	}

	return true, nil
}

//修改数据
func (p *ProductDao) Update(product *model.Product) (err error) {
	if _, err = p.ID(product.Id).Cols("product_num").Update(product); err != nil {
		return err
	}

	return
}

//根据id查询数据
func (p *ProductDao) SelectById(id int64) (product *model.Product, err error) {
	product = &model.Product{}
	if _, err = p.ID(id).Get(product); err != nil {
		return nil, err
	}

	return
}

//查询列表
func (p *ProductDao) SelectAll() (list []*model.Product, err error) {
	list = make([]*model.Product, 0)
	if err = p.Find(&list); err != nil {
		return nil, err
	}
	return
}
